#include <iostream>
#include <random>
#include <dds/dds.h>
#include "end_atomic_0826_result_distribution_service.h"
#include "../../../include/log_client/LogClient.h"

// DDS实体句柄
static dds_entity_t participant;
static dds_entity_t topic;
static dds_entity_t subscriber;
static dds_entity_t reader;

// 简化结构体名称
typedef end_atomic_0826_result_distribution_service_ResultDistributionOutput TransportOutput;

// 清理DDS资源
static void cleanup()
{
    if (reader != DDS_HANDLE_NIL)
        dds_delete(reader);
    if (subscriber != DDS_HANDLE_NIL)
        dds_delete(subscriber);
    if (topic != DDS_HANDLE_NIL)
        dds_delete(topic);
    if (participant != DDS_HANDLE_NIL)
        dds_delete(participant);
}

// 生成随机结果数据（用于测试）
TransportOutput generate_random_transport_data()
{
    static std::mt19937 rng(std::random_device{}());
    
    // 定义各种随机分布
    std::uniform_int_distribution<int32_t> solution_valid_dist(0, 1);          // 解有效性：0-无效，1-有效
    std::uniform_real_distribution<double> sol_time_dist(0.0, 1e9);             // 解算时间
    std::uniform_real_distribution<double> latitude_dist(-90.0, 90.0);          // 纬度
    std::uniform_real_distribution<double> longitude_dist(-180.0, 180.0);       // 经度
    std::uniform_real_distribution<float> altitude_dist(-1000.0f, 10000.0f);    // 高度
    std::uniform_real_distribution<float> pos_std_dist(0.0f, 10.0f);            // 位置标准差
    std::uniform_real_distribution<float> velocity_dist(-100.0f, 100.0f);       // 速度分量
    std::uniform_real_distribution<float> vel_std_dist(0.0f, 5.0f);             // 速度标准差
    std::uniform_real_distribution<float> roll_pitch_dist(-180.0f, 180.0f);     // 横滚角、俯仰角
    std::uniform_real_distribution<float> heading_dist(0.0f, 360.0f);           // 航向角
    std::uniform_real_distribution<float> att_std_dist(0.0f, 2.0f);             // 姿态标准差
    std::uniform_int_distribution<int32_t> sensor_id_dist(0, 1000);             // 传感器ID
    std::uniform_real_distribution<double> raw_error_dist(0.0, 100.0);          // 原始误差
    std::uniform_real_distribution<double> position_dist(-1e6, 1e6);            // X/Y位置
    std::uniform_real_distribution<double> timestamp_dist(0.0, 1e18);           // 时间戳
    std::uniform_int_distribution<int32_t> count_dist(0, 1000);                 // 成功/失败计数
    std::uniform_int_distribution<int32_t> type_dist(0, 3);                     // 返回类型：0-3

    TransportOutput data;
    data.solution_valid = solution_valid_dist(rng);
    data.sol_time = sol_time_dist(rng);
    data.latitude = latitude_dist(rng);
    data.longitude = longitude_dist(rng);
    data.altitude = altitude_dist(rng);
    data.pos_std_lat = pos_std_dist(rng);
    data.pos_std_lon = pos_std_dist(rng);
    data.pos_std_alt = pos_std_dist(rng);
    data.velocity_east = velocity_dist(rng);
    data.velocity_north = velocity_dist(rng);
    data.velocity_up = velocity_dist(rng);
    data.vel_std_east = vel_std_dist(rng);
    data.vel_std_north = vel_std_dist(rng);
    data.vel_std_up = vel_std_dist(rng);
    data.attitude_roll = roll_pitch_dist(rng);
    data.attitude_pitch = roll_pitch_dist(rng);
    data.attitude_heading = heading_dist(rng);
    data.att_std_roll = att_std_dist(rng);
    data.att_std_pitch = att_std_dist(rng);
    data.att_std_heading = att_std_dist(rng);
    data.sensor_id = sensor_id_dist(rng);
    data.raw_error = raw_error_dist(rng);
    data.position_x = position_dist(rng);
    data.position_y = position_dist(rng);
    data.timestamp = timestamp_dist(rng);
    data.success_count = count_dist(rng);
    data.fail_count = count_dist(rng);
    data.return_type = type_dist(rng);
    
    return data;
}

int main()
{
    // 初始化日志
    LogClient::getInstance().init("end_atomic_0826_result_distribution_service", "end_atomic_0826_result_distribution_service");

    dds_return_t rc;
    void* samples[1];       // 存储DDS样本的数组（最多1个样本）
    dds_sample_info_t info; // 样本元信息

    // 1. 初始化DDS参与者
    participant = dds_create_participant(DDS_DOMAIN_DEFAULT, NULL, NULL);
    if (participant < 0)
    {
        std::cerr << "错误：创建参与者失败，原因：" << dds_strretcode(-participant) << std::endl;
        LogClient::getInstance().logError("创建参与者失败，原因：" + std::string(dds_strretcode(-participant)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 2. 创建主题（与发布者保持一致）
    topic = dds_create_topic(
        participant,
        &end_atomic_0826_result_distribution_service_ResultDistributionOutput_desc,
        "end_atomic_0826_result_distribution_service",  // 主题名称
        NULL, NULL);
    if (topic < 0)
    {
        std::cerr << "错误：创建主题失败，原因：" << dds_strretcode(-topic) << std::endl;
        LogClient::getInstance().logError("创建主题失败，原因：" + std::string(dds_strretcode(-topic)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 3. 创建订阅者
    subscriber = dds_create_subscriber(participant, NULL, NULL);
    if (subscriber < 0)
    {
        std::cerr << "错误：创建订阅者失败，原因：" << dds_strretcode(-subscriber) << std::endl;
        LogClient::getInstance().logError("创建订阅者失败，原因：" + std::string(dds_strretcode(-subscriber)));
        cleanup();
        return EXIT_FAILURE;
    }

    // 4. 创建数据读取器
    dds_qos_t* qos = dds_create_qos();
    dds_qset_reliability(qos, DDS_RELIABILITY_RELIABLE, DDS_SECS(10));
    dds_qset_history(qos, DDS_HISTORY_KEEP_LAST, 10);

    reader = dds_create_reader(subscriber, topic, qos, NULL);
    dds_delete_qos(qos);

    if (reader < 0)
    {
        std::cerr << "错误：创建读取器失败，原因：" << dds_strretcode(-reader) << std::endl;
        LogClient::getInstance().logError("创建读取器失败，原因：" + std::string(dds_strretcode(-reader)));
        cleanup();
        return EXIT_FAILURE;
    }

    std::cout << "DDS结果分布服务订阅者已启动，等待接收数据..." << std::endl;
    std::cout << "主题: end_atomic_0826_result_distribution_service" << std::endl;  // 修正主题名称
    std::cout << "按Ctrl+C终止程序" << std::endl;
    LogClient::getInstance().logInfo("DDS结果分布服务订阅者已启动，等待接收数据...\n主题: end_atomic_0826_result_distribution_service\n按Ctrl+C终止程序");

    // 5. 循环读取数据
    int count = 0;
    while (true)
    {
        // 分配样本内存
        samples[0] = end_atomic_0826_result_distribution_service_ResultDistributionOutput__alloc();
        if (samples[0] == NULL)
        {
            std::cerr << "错误：分配样本内存失败" << std::endl;
            LogClient::getInstance().logError("分配样本内存失败");
            cleanup();
            return EXIT_FAILURE;
        }

        // 从读取器中获取数据
        rc = dds_take(reader, samples, &info, 1, 1);
        if (rc < 0)
        {
            std::cerr << "错误：dds_take失败，原因：" << dds_strretcode(-rc) << std::endl;
            LogClient::getInstance().logError("dds_take失败，原因：" + std::string(dds_strretcode(-rc)));
            end_atomic_0826_result_distribution_service_ResultDistributionOutput_free(samples[0], DDS_FREE_ALL);
            cleanup();
            return EXIT_FAILURE;
        }

        // 检查是否有有效数据
        if (rc > 0 && info.valid_data)
        {
            // 转换为目标结构体类型
            TransportOutput* data = (TransportOutput*)samples[0];
            count++;

            // 构建日志信息
            const char* solution_valid_str = (data->solution_valid == 0) ? "无效" : "有效";
            const char* type_str[] = {"成功", "警告", "错误", "超时"};
            int32_t type_idx = (data->return_type >= 0 && data->return_type < 4) ? data->return_type : 0;

            std::string log_info = "接收到到结果数据，第" + std::to_string(count) + "次\n";
            log_info += "源时间戳: " + std::to_string(info.source_timestamp) + "\n";
            log_info += "解有效性: " + std::string(solution_valid_str) + " (" + std::to_string(data->solution_valid) + ")\n";
            log_info += "解算时间: " + std::to_string(data->sol_time) + "\n";
            log_info += "纬度: " + std::to_string(data->latitude) + "° 经度: " + std::to_string(data->longitude) + "°\n";
            log_info += "高度: " + std::to_string(data->altitude) + "m 位置标准差(lat/lon/alt): " 
                      + std::to_string(data->pos_std_lat) + "/" 
                      + std::to_string(data->pos_std_lon) + "/" 
                      + std::to_string(data->pos_std_alt) + "\n";
            log_info += "速度(east/north/up): " 
                      + std::to_string(data->velocity_east) + "/" 
                      + std::to_string(data->velocity_north) + "/" 
                      + std::to_string(data->velocity_up) + "m/s\n";
            log_info += "速度标准差(east/north/up): " 
                      + std::to_string(data->vel_std_east) + "/" 
                      + std::to_string(data->vel_std_north) + "/" 
                      + std::to_string(data->vel_std_up) + "\n";
            log_info += "姿态(roll/pitch/heading): " 
                      + std::to_string(data->attitude_roll) + "/" 
                      + std::to_string(data->attitude_pitch) + "/" 
                      + std::to_string(data->attitude_heading) + "°\n";
            log_info += "姿态标准差(roll/pitch/heading): " 
                      + std::to_string(data->att_std_roll) + "/" 
                      + std::to_string(data->att_std_pitch) + "/" 
                      + std::to_string(data->att_std_heading) + "\n";
            log_info += "传感器ID: " + std::to_string(data->sensor_id) + "\n";
            log_info += "原始误差: " + std::to_string(data->raw_error) + "\n";
            log_info += "X位置: " + std::to_string(data->position_x) + " Y位置: " + std::to_string(data->position_y) + "\n";
            log_info += "数据时间戳: " + std::to_string(data->timestamp) + "\n";
            log_info += "成功计数: " + std::to_string(data->success_count) + " 失败计数: " + std::to_string(data->fail_count) + "\n";
            log_info += "返回类型: " + std::string(type_str[type_idx]) + " (" + std::to_string(data->return_type) + ")\n";

            std::cout << log_info << std::endl;
            LogClient::getInstance().logInfo(log_info);
        }

        // 释放样本内存
        end_atomic_0826_result_distribution_service_ResultDistributionOutput_free(samples[0], DDS_FREE_ALL);

        // 休眠100ms避免CPU占用过高
        dds_sleepfor(DDS_MSECS(100));
    }

    // 清理资源（实际不会执行到）
    cleanup();
    return EXIT_SUCCESS;
}